<?php
namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\Teacher as TeacherModel;
use think\Request;
use think\Validate; // 引入 Validate 类
use think\Db;

class Teacher extends Api
{
    // 不需要登录和权限校验
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 保存教师信息（新增或更新）
     */
    public function save(Request $request)
    {
        // 获取请求数据
        $user=$this->auth->getUser();
        if(!isset($_POST['username'])){
            $username="JS".$user["mobile"];
            $user2 = model("\app\common\model\User")::where('username', $username)->find();
            if (!$user2) {
                $salt = rand(100000, 999999);
                $user0= model("\app\common\model\User")::where('id', $user['uid'])->find();
                $user = model("\app\common\model\User")::create([
                    'username' => $username,
                    'mobile' => $user0["mobile"],
                    'nickname' => $user0["nickname"],
                    'email' => $user0["email"],
                    'salt' => $salt,
                    'password' => md5(md5($user["mobile"]) . $salt),
                    'avatar' => $user0["avatar"],
                    'gender' => $user0["gender"],
                    'birthday' => $user0["birthday"],
                    'group_id'=>2, // 用户组ID为2，表示教师用户
                    'status'=>3, // 状态为3 已经注册但未认证
                ]);
                $user['uid']=$user->id;
                $isregister=1;
            }else{
                $user['uid']=$user2['id'];
                $isregister=0;
            }
        }else{
            $isregister=0;
        }
        
        // 检查是否已有申请记录
        $existingApplication = Db::name('eb_class_teacher')->where('teacher_id', $user['uid'])->find();
        if ($existingApplication) {
            $statusText = '';
            switch ($existingApplication['status']) {
                case 1:
                    $statusText = '审核通过';
                    break;
                case null:
                case 0:
                    $statusText = '等待审核';
                    break;
                case -1:
                    $statusText = '审核不通过';
                    break;
                default:
                    $statusText = '等待审核';
                    break;
            }
            return json([
                'code' => 0, 
                'msg' => '您已经申请过教师资格审核，请不要重复申请。当前申请状态：' . $statusText
            ]);
        }
        
        $data = $_POST;
        $data['teacher_id']=$user['uid'];
        // 实例化验证器
        $validate = new Validate();
        $validate->rule([
            'name' => 'max:50',
            'gender' => 'in:男,女',
            'birthdate' => 'date',
            'major' => 'max:100',
            'political' => 'max:50',
            'contact' => 'max:20',
            'resume' => 'max:5000',
        ]);

        // 验证数据
        if (!$validate->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        // 实例化模型
        $model = new TeacherModel();

        // 如果存在 ID，则为更新操作
        $existingRecord = $model->where('teacher_id', $data['teacher_id'])->find();
        if(!isset($data['birthdate'])||$data['birthdate']==""){
            $data['birthdate']=null;
        }
        if ($existingRecord) {
            // 如果存在，则更新
            $data['update_time'] = date('Y-m-d H:i:s');
            $result = $model->where('teacher_id', $data['teacher_id'])->update($data);
        } else {
            // 如果不存在，则插入
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['add_time'] = time() ;
            $data['status'] = 'pending';
            $result = $model->save($data);
        }
        $userinfo=Db::name('user')->where('id',$user['uid'])->find();
        $teacherinfo=Db::name('eb_class_teacher')->where('teacher_id',$user['uid'])->find();
        $teacherinfo=$teacherinfo?$teacherinfo:[];
        $data=array_merge( $this->UserFilter($userinfo),$teacherinfo);

        // 返回结果
        return json([
            'code' => 200,
            'data' =>$data,
            'msg' => $isregister?"注册成功,需管理员审核通过才能正常使用":'保存成功',
        ]);
    }


    /**
     * 录入申请单位、姓名、性别、出生日期、专业课类别、政治面貌、联系方式和专业简历
     */
    public function addApplicationUnit(Request $request)
    {
        // 获取请求数据
        $user=$this->auth->getUser();
        
        // 检查是否已有申请记录
        $existingApplication = Db::name('eb_class_teacher')->where('teacher_id', $user['uid'])->find();
        if ($existingApplication) {
            $statusText = '';
            switch ($existingApplication['status']) {
                case 1:
                    $statusText = '审核通过';
                    break;
                case null:
                case 0:
                    $statusText = '等待审核';
                    break;
                case -1:
                    $statusText = '审核不通过';
                    break;
                default:
                    $statusText = '等待审核';
                    break;
            }
            if($statusText == '等待审核') {
                return json([
                    'code' => 400,
                    'msg' => '您已经申请过教师资格审核，请不要重复申请。当前申请状态：' . $statusText
                ]);
            }else if($statusText == '审核通过'){
                return json([
                    'code' => 400,
                    'msg' => '您已经申请过教师资格审核并且审核通过，请不要重复申请。'
                ]);
            }else if ($statusText == '审核不通过'){
                return json([
                    'code' => 400,
                    'msg' => '您已经申请过教师资格审核并且审核不通过，可能是因为您的申请信息有误或不齐全，请联系管理员处理。'
                ]);
            }
        }
        
        $data = $request->post();
        if (empty($data)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        // 实例化验证器
        $validate = new Validate();
        $validate->rule([
            'school_id' => 'require',
            'name' => 'require|max:50',
            'gender' => 'require|in:男,女',
            'birthdate' => 'date',
            'major' => 'max:100',
            'political' => 'max:50',
            'contact' => 'max:20',
            'resume' => 'max:65535',
        ]);

        // 验证数据
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 实例化模型
        $model = new TeacherModel();
        $data['add_time'] = time();
        $data['teacher_id']=$user['uid'];
        $data['status'] = 'pending';
        // 保存数据
        $result = $model->save($data);
        if ($result) {
            $contact = isset($data['contact']) ? trim($data['contact']) : '';
            $isMobile = preg_match('/^1[3-9]\d{9}$/', $contact);
            $rawPassword = $isMobile ? $contact : '123456';
            $currentMobile = isset($user['mobile']) ? trim($user['mobile']) : '';
            $accountUsername = $isMobile ? $contact : ('JS'.$currentMobile);
            $mobileField = $isMobile ? $contact : $currentMobile;
            $salt = rand(100000, 999999);
            $passwordHashed = md5(md5($rawPassword).$salt);
            $userData = [
                'username' => $accountUsername,
                'mobile' => $mobileField,
                'nickname' => (isset($data['name']) && trim($data['name']) !== '') ? trim($data['name']) : $accountUsername,
                'salt' => $salt,
                'password' => $passwordHashed,
                'group_id' => 2,
                'status' => 'pending',
                'weigh' => 0,
                'createtime' => time(),
                'updatetime' => time()
            ];
            try {
                $newUserId = Db::name('user')->insertGetId($userData);
            } catch (\Exception $e) {
                file_put_contents($_SERVER["DOCUMENT_ROOT"]."/../teacher_add_application_unit_error.log", 'user_insert: '.$e->getMessage()."\n", FILE_APPEND);
                $newUserId = 0;
            }
            return json(['code' => 200, 'msg' => '正在申请老师资格，请等待审核', 'data' => ['user_id' => $newUserId]]);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }

    public function approveApplication(Request $request)
    {
        $admin = $this->auth->getUser(true);
        $teacherId = intval($request->post('teacher_id', 0));
        $id = intval($request->post('id', 0));
        if ($teacherId <= 0 && $id <= 0) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        try {
            if ($id > 0) {
                $row = Db::name('eb_class_teacher')->where('id', $id)->find();
                if (!$row) return json(['code' => 404, 'msg' => '记录不存在']);
                $teacherId = intval($row['teacher_id']);
            }
            Db::name('eb_class_teacher')->where('teacher_id', $teacherId)->update([
                'status' => 'approved',
                'audit_time' => time()
            ]);
            Db::name('user')->where('id', $teacherId)->update([
                'status' => 'normal',
                'updatetime' => time()
            ]);
            return json(['code' => 200, 'msg' => '审核通过，用户已激活']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '操作失败: '.$e->getMessage()]);
        }
    }

    public function rejectApplication(Request $request)
    {
        $admin = $this->auth->getUser(true);
        $teacherId = intval($request->post('teacher_id', 0));
        $id = intval($request->post('id', 0));
        $reason = trim($request->post('refuse_reason', ''));
        if ($teacherId <= 0 && $id <= 0) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        try {
            if ($id > 0) {
                $row = Db::name('eb_class_teacher')->where('id', $id)->find();
                if (!$row) return json(['code' => 404, 'msg' => '记录不存在']);
                $teacherId = intval($row['teacher_id']);
            }
            Db::name('eb_class_teacher')->where('teacher_id', $teacherId)->update([
                'status' => 'rejected',
                'audit_time' => time(),
                'refuse_reason' => $reason
            ]);
            return json(['code' => 200, 'msg' => '已拒绝']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '操作失败: '.$e->getMessage()]);
        }
    }

    public function withdrawApplication(Request $request)
    {
        $user = $this->auth->getUser(true);
        $teacherId = intval($request->post('teacher_id', 0));
        $id = intval($request->post('id', 0));
        if ($teacherId <= 0 && $id <= 0) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        try {
            if ($id > 0) {
                $row = Db::name('eb_class_teacher')->where('id', $id)->find();
                if (!$row) return json(['code' => 404, 'msg' => '记录不存在']);
                $teacherId = intval($row['teacher_id']);
            }
            $affected = Db::name('eb_class_teacher')->where('teacher_id', $teacherId)->update([
                'status' => 'withdrawn',
                'audit_time' => time()
            ]);
            Db::name('user')->where('id', $teacherId)->update([
                'status' => 'disabled',
                'updatetime' => time()
            ]);
            return json(['code' => 200, 'msg' => '已撤回', 'data' => ['affected' => $affected]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '操作失败: '.$e->getMessage()]);
        }
    }

    //列出当前用户的申请的教师资格信息，假设有多个申请，请汇总审核中、审核通过、审核不通过记录，只需要列出申请的单位、申请时间、审核状态、审核时间、不通过原因
    public function getApplicationList(Request $request)
    {
        $user = $this->auth->getUser();
        $userId = $user['uid'];
        $rows = Db::name('eb_class_teacher')
            ->alias('t')
            ->join('fa_user u', 't.teacher_id = u.id')
            ->where('t.teacher_id', $userId)
            ->field('t.id,t.application_unit,t.add_time,t.status,t.audit_time,t.refuse_reason,u.username,u.mobile,u.nickname')
            ->order('t.add_time desc')
            ->select();
        $list = [];
        if ($rows) {
            foreach ($rows as $r) {
                $statusRaw = isset($r['status']) ? $r['status'] : null;
                $statusNum = 0;
                $statusText = '等待审核';
                if ($statusRaw === 'approved' || $statusRaw === 1) { $statusNum = 1; $statusText = '审核通过'; }
                elseif ($statusRaw === 'rejected' || $statusRaw === -1) { $statusNum = -1; $statusText = '审核不通过'; }
                elseif ($statusRaw === 'withdrawn' || $statusRaw === -2) { $statusNum = -2; $statusText = '已撤回'; }
                $list[] = [
                    'id' => $r['id'],
                    'school_name' => isset($r['application_unit']) ? $r['application_unit'] : '',
                    'name' => isset($r['nickname']) && $r['nickname'] ? $r['nickname'] : (isset($r['username']) ? $r['username'] : ''),
                    'create_time' => isset($r['add_time']) && $r['add_time'] ? date('Y-m-d H:i:s', $r['add_time']) : null,
                    'audit_time' => isset($r['audit_time']) && $r['audit_time'] ? date('Y-m-d H:i:s', $r['audit_time']) : null,
                    'status' => $statusNum,
                    'status_text' => $statusText,
                    'refuse_reason' => isset($r['refuse_reason']) ? $r['refuse_reason'] : ''
                ];
            }
        }
        return json(['code' => 200, 'data' => $list, 'msg' => '查询成功']);
    }

    public function getApplicationInfo(Request $request)
    {
        $user = $this->auth->getUser();
        $userId = $user['uid'];
        $id = intval($request->get('id', 0));
        if ($id <= 0) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        $r = Db::name('eb_class_teacher')
            ->alias('t')
            ->join('fa_user u', 't.teacher_id = u.id')
            ->where('t.teacher_id', $userId)
            ->where('t.id', $id)
            ->field('t.id,t.application_unit,t.name,t.gender,t.birthdate,t.major,t.political,t.contact,t.resume,t.add_time,t.audit_time,t.status,t.refuse_reason,u.username,u.nickname')
            ->find();
        if (!$r) {
            return json(['code' => 404, 'msg' => '记录不存在', 'data' => []]);
        }
        $statusRaw = isset($r['status']) ? $r['status'] : null;
        $statusNum = 0;
        $statusText = '等待审核';
        if ($statusRaw === 'approved' || $statusRaw === 1) { $statusNum = 1; $statusText = '审核通过'; }
        elseif ($statusRaw === 'rejected' || $statusRaw === -1) { $statusNum = -1; $statusText = '审核不通过'; }
        elseif ($statusRaw === 'withdrawn' || $statusRaw === -2) { $statusNum = -2; $statusText = '已撤回'; }
        $data = [
            'id' => $r['id'],
            'school_name' => isset($r['application_unit']) ? $r['application_unit'] : '',
            'name' => isset($r['name']) && $r['name'] ? $r['name'] : (isset($r['nickname']) && $r['nickname'] ? $r['nickname'] : (isset($r['username']) ? $r['username'] : '')),
            'gender' => isset($r['gender']) ? $r['gender'] : '',
            'birthdate' => isset($r['birthdate']) ? $r['birthdate'] : '',
            'major' => isset($r['major']) ? $r['major'] : '',
            'political' => isset($r['political']) ? $r['political'] : '',
            'contact' => isset($r['contact']) ? $r['contact'] : '',
            'resume' => isset($r['resume']) ? $r['resume'] : '',
            'create_time' => isset($r['add_time']) && $r['add_time'] ? date('Y-m-d H:i:s', $r['add_time']) : null,
            'audit_time' => isset($r['audit_time']) && $r['audit_time'] ? date('Y-m-d H:i:s', $r['audit_time']) : null,
            'status' => $statusNum,
            'status_text' => $statusText,
            'refuse_reason' => isset($r['refuse_reason']) ? $r['refuse_reason'] : ''
        ];
        return json(['code' => 200, 'data' => $data, 'msg' => '查询成功']);
    }


}
